package wikitools.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import wikitools.model.Article;
import wikitools.model.TextBase;
import wikitools.model.TextBaseFactory;
import wikitools.util.XMLUtil;

public class CreateArticle extends HttpServlet{


    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public CreateArticle() {
        super();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        ServletUtil.alert("HAHA", resp);
    }

    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        System.out.println("A Create Article Request!........");
        createArticle(request, response);
    }


    private void createArticle(HttpServletRequest request,
            HttpServletResponse response) throws IOException{
        String title = request.getParameter("title");
        String content = request.getParameter("content");
        //TODO: Deal with author
        Article newArticle = new Article(title, title, "anonymous", content);
        TextBase db = TextBaseFactory.getTextBase();
        db.createArticle(newArticle);       
        response.setStatus(201); //resource created
        ServletUtil.writeXML(XMLUtil.toXML(newArticle), response);
        
    }
    
}
